package tests;

import static org.junit.Assert.*;

import java.util.ArrayList;

import logic.Constraint;
import logic.Sudoku;
import logic.cell;

import org.junit.Test;

import com.rits.cloning.Cloner;

public class ConstraintTests {
	ArrayList<Integer> possibleVlaues = new ArrayList<Integer>();
	Cloner cloner = new Cloner();

	private void buildPossibleValues()
	{
		for(int i = 1; i < 10; i++)			
		{
			possibleVlaues.add(i);
		}
	}
	
	/**
	 *  test single constraint and cell
	 */
	@Test
	public void test() {
		buildPossibleValues();
		Constraint constraint = new Constraint();
		addCells(constraint);
		assertFalse(constraint.violated());
		assertFalse(constraint.satisfied());
		
		for(int i = 1; i < 10;i++)
		{
			constraint.getCells().get(i-1).setCurrentValue(i);
		}
		
		assertFalse(constraint.violated());
		assertTrue(constraint.satisfied());
		
		constraint.getCells().get(2).setCurrentValue(1);
		assertTrue(constraint.violated());
		assertFalse(constraint.satisfied());
		
		constraint.getCells().get(2).setCurrentValue(3);
		assertFalse(constraint.violated());
		
		constraint.getCells().get(8).setCurrentValue(cell.BLANK);
		assertFalse(constraint.violated());
		assertFalse(constraint.satisfied());
	}
	
	/**
	 * test sudoku solvable by logic
	 */
	@Test
	public void test2()	
	{
		Constraint constraint = new Constraint();
		Constraint constraintTwo = new Constraint();
		buildPossibleValues();
		for(int n =0; n < 8;n++)
		{
			cell cellToAdd = new cell(cloner.deepClone(possibleVlaues));
			constraint.addCell(cellToAdd);
			cellToAdd.addConstraint(constraint);
		}
		
		for(int i =0; i < 7;i++) // first 7 cells have values 1 - 7
		{
			constraint.getCells().get(i).setCurrentValue(i + 1);
		}
		
		for(int n =0; n < 8;n++)
		{
			cell cellToAdd = new cell(cloner.deepClone(possibleVlaues));
			constraintTwo.addCell(cellToAdd);
			cellToAdd.addConstraint(constraintTwo);
		}
		
		constraintTwo.getCells().get(0).setCurrentValue(8);
		
		
		cell cell2 = new cell(new ArrayList<Integer>());
		
//		add cell to both constraints
		constraint.addCell(cell2);	
		cell2.addConstraint(constraint);
		
		constraintTwo.addCell(cell2);	
		cell2.addConstraint(constraintTwo);
		
		
		Sudoku test = new Sudoku(0);
		
		assertTrue(test.cellCanBeDerivedLogicly(cell2));
		assertFalse(constraint.violated());
		assertFalse(constraintTwo.violated());
		assertFalse(constraint.satisfied());
		assertFalse(constraintTwo.satisfied());
		
		constraintTwo.getCells().get(0).setCurrentValue(cell.BLANK);
		assertFalse(test.cellCanBeDerivedLogicly(cell2));
	}
	
	

	private void addCells(Constraint constraint)
	{
		for(int n =0; n < 9;n++)
		{
			cell cellToAdd = new cell(cloner.deepClone(possibleVlaues));
			constraint.addCell(cellToAdd);
			cellToAdd.addConstraint(constraint);
		}
	}
}
